import 'dart:io' show Platform;
import 'package:flutter_dotenv/flutter_dotenv.dart';

class EnvLoader {
  static final EnvLoader _instance = EnvLoader._internal();
  factory EnvLoader() => _instance;
  EnvLoader._internal();

  bool _isInitialized = false;

  /// 初始化环境变量
  Future<void> init() async {
    if (_isInitialized) return;

    // 加载.env文件
    await dotenv.load(fileName: ".env");
    _isInitialized = true;
  }

  /// 获取环境变量值
  String? get(String key) {
    // 优先从系统环境变量获取
    final value = Platform.environment[key];
    if (value != null) return value;

    // 从.env文件获取
    return dotenv.env[key];
  }

  /// 获取环境变量值，如果不存在则返回默认值
  String getOrDefault(String key, String defaultValue) {
    return get(key) ?? defaultValue;
  }

  /// 替换字符串中的环境变量引用
  /// 例如: "Hello ${USER_NAME}" 将被替换为 "Hello John"
  String replaceEnvVars(String input) {
    final regex = RegExp(r'\$\{([^}]+)\}');
    return input.replaceAllMapped(regex, (match) {
      final key = match.group(1)!;
      return getOrDefault(key, '');
    });
  }
}
